package datastructure.sort;

/**
 * @author MaoLin Wang
 * @date 2020/10/7 3:52 下午
 */
public class BubbleSort {
    public static int[] bubbleSort (int[] addr){
        if (addr.length<=1){
            return addr;
        }
        boolean changed=false;
        for (int i = 0; i < addr.length; i++) {
            for (int j = addr.length-1; j >i ; j--) {
                if (addr[j]<addr[j-1]){
                    swap(j,j-1,addr);
                    changed=true;
                }
            }
            if (!changed){
                return addr;
            }else {
                changed=false;
            }
        }
        return addr;
    }

    public static int[] bubbleSort2 (int[] addr) {
        if(addr.length<=1){
            return addr;
        }
        boolean changed=false;

        for (int i = 0; i <addr.length; i++) {
           /* for (int j = 0; j < addr.length-1-i; j++) {
                //每轮把大的挪到最后一个
                if (addr[j]>addr[j+1]){
                    swap(j,j+1,addr);
                    changed=true;
                }
            }*/
            //每次把小的挪到第一个
            for (int j = addr.length-1; j >i+1 ; j--) {
                if (addr[j]<addr[j-1]){
                    swap(j,j-1,addr);
                    changed=true;
                }
            }
            if (!changed){
                return addr;
            }
            changed=false;
        }
        return addr;
    }

    private static void swap(int i, int j, int[] addr) {
        int temp=addr[i];
        addr[i]=addr[j];
        addr[j] = temp;
    }

    public static void main(String[] args) {
        int[] addr=new int[]{1,12,30,5,4,42,1,234,23,5,46,7};
        int[] ints = bubbleSort(addr);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }
}
